package com.aaa.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @author ：zhouhangyong
 * @date ：Created in 2022/6/24 19:58
 * @description：上传图片
 * @modified By：
 * @version:
 */
public class ImgLoad {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    static String accessKeyId = "LTAI5tGgLHQAnsk3AfhoHY6a";
    static String accessKeySecret = "VRSOhrQFMmGJNGGZIooawbJn77nKS4";
    // 填写Bucket名称，例如examplebucket。
    static String bucketName = "zhouhangyong";

    static String objectName;

    public static PutObjectRequest imgLoad(MultipartFile file, Boolean boo) {

        //获取原始文件名
        String filename = file.getOriginalFilename();


        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        objectName = UUID.randomUUID() + filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //原始文件

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));

            System.out.println("put" + putObjectRequest);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);


            return putObjectRequest;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return null;
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
    }
    public static String urlLoad(PutObjectRequest putObjectRequest) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置签名URL过期时间，单位为毫秒。
        Date expiration = new Date(new Date().getTime());
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        String substring = url.toString().substring(0, url.toString().indexOf("?Expires"));
        // 上传字符串。
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        return substring;
    }
}
